package com.yuexiao.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.yuexiao.config.RedisUtil;
import com.yuexiao.entity.ResultInfo;
import com.yuexiao.pojo.User;
import com.yuexiao.service.UserService;
import com.yuexiao.util.SendMsgTools;
import com.yuexiao.util.Tool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @ClassName:UserController
 * @Auther: YUEXIAO
 * @Description: 用户操作控制器
 * @Date: 2022/8/12 22:58
 * @Version: v1.0
 */
@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {

    @Reference
    private UserService userService;
    @Autowired
    private RedisUtil redisUtil;


    /**
     * 发送短信验证码
     *
     * @param map     Map 用于接收前台传入的手机号
     * @param request 无需手动传入
     * @return ResultInfo 返回结果对象
     * @throws UnsupportedEncodingException
     */
    @PostMapping("/sendMsg")
    public ResultInfo sendMsg(@RequestBody Map map, HttpServletRequest request) throws UnsupportedEncodingException {

        //获取手机号
        String phone = map.get("phone").toString();

        //查询手机号是否存在
        User userByPhone = userService.getUserByPhone(phone);
        if (userByPhone == null || userByPhone.getId() == null) {
            return ResultInfo.error("该用户不存在");
        }
        //发送验证码
        String code = SendMsgTools.printD(phone);
        if (code != null && code != "") {
            //存入redis
            redisUtil.set(phone,Tool.getEncoder(code),60);
            return ResultInfo.success(null);
        }

        return ResultInfo.error("发送失败");
    }



}
